const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, extractNumber, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');

// 获取部门列表
// 参数 { "dept_name": "张三" }
router.get('/', authenticateToken, async (req, res) => {
    try {
        const { dept_name } = req.query;
        let sql = 'SELECT * FROM department WHERE 1=1';
        if (dept_name) {
            sql += ` AND dept_name like '%${dept_name}%'`;
        }

        let [result] = await db.execute(sql);

        result.forEach(item => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss');
        });

        await logUserOperation(req, '查询', '获取部门列表', '获取部门列表成功', '成功');
        res.json({
            success: true,
            message: '获取部门列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取部门列表失败:', error);
        await logUserOperation(req, '查询', '获取部门列表', '获取部门列表失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取部门列表失败',
            error: error.message
        });
    }
});

// 新增部门
router.put("/add", authenticateToken, async (req, res) => {
    try {
        const { dept_name } = req.body;
        const create_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
        // 获取数据库中最大的dept_id A001
        const [maxDeptId] = await db.execute(
            'SELECT MAX(dept_id) AS max_dept_id FROM department'
        );

        let nextId = 1;
        if (maxDeptId[0].max_dept_id) {
            // 提取数字部分并加1
            const currentNumber = extractNumber(maxDeptId[0].max_dept_id);
            nextId = currentNumber + 1;
        }
        const dept_id = generateString('A', nextId, 3);
        let sql = `INSERT INTO department (dept_id, dept_name, create_time) VALUES (?, ?, ?)`;
        let params = [dept_id, dept_name, create_time];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '添加', '新增部门', '新增部门成功', '成功');
        res.json({
            success: true,
            message: '新增部门成功',
            data: result
        });
    } catch (error) {
        console.error('新增部门失败:', error);
        await logUserOperation(req, '添加', '新增部门', '新增部门失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '新增部门失败',
            error: error.message
        });
    }
});

// 更新部门
router.post("/update", authenticateToken, async (req, res) => {
    try {
        const { dept_id, dept_name } = req.body;
        let sql = `UPDATE department SET dept_name = ? WHERE dept_id = ?`;
        let params = [dept_name, dept_id];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '更新', '更新部门', '更新部门成功', '成功');
        res.json({
            success: true,
            message: '更新部门成功',
            data: result
        });
    } catch (error) {
        console.error('更新部门失败:', error);
        await logUserOperation(req, '更新', '更新部门', '更新部门失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '更新部门失败',
            error: error.message
        });
    }
});

// 删除部门
router.delete("/delete", authenticateToken, async (req, res) => {
    try {
        const { dept_id } = req.body;

        // 验证参数
        if (!dept_id) {
            return res.status(400).json({
                success: false,
                message: '部门ID不能为空'
            });
        }
        // 检查部门是否存在
        const [checkResult] = await db.execute('SELECT dept_id, dept_name FROM department WHERE dept_id = ?', [dept_id]);
        if (checkResult.length === 0) {
            return res.status(404).json({
                success: false,
                message: '部门不存在'
            });
        }

        // 检查是否有员工关联到这个部门
        const [employeeCheck] = await db.execute('SELECT COUNT(*) as count FROM employee WHERE dept_id = ?', [dept_id]);
        if (employeeCheck[0].count > 0) {
            return res.status(400).json({
                success: false,
                message: `部门"${checkResult[0].dept_name}"下还有${employeeCheck[0].count}名员工，无法删除。请先移除或转移该部门下的所有员工。`,
                data: {
                    dept_name: checkResult[0].dept_name,
                    employee_count: employeeCheck[0].count
                }
            });
        }

        // 执行删除操作
        let sql = `DELETE FROM department WHERE dept_id = ?`;
        let params = [dept_id];
        const [result] = await db.execute(sql, params);
        
        if (result.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                message: '删除失败，部门不存在'
            });
        }

        await logUserOperation(req, '删除', '删除部门', '删除部门成功', '成功');
        res.json({
            success: true,
            message: '删除部门成功',
            data: result
        });
    } catch (error) {
        await logUserOperation(req, '删除', '删除部门', '删除部门失败', '失败', error.message);
        if (error.code === 'ER_ROW_IS_REFERENCED_2' || error.message.includes('ER_ROW_IS_REFERENCED')) {
            return res.status(400).json({
                success: false,
                message: '该部门下还有员工，无法删除。请先移除或转移该部门下的所有员工。',
                error: error.message
            });
        }
        console.error('删除部门失败:', error);
        res.status(500).json({
            success: false,
            message: '删除部门失败',
            error: error.message
        });
    }
});

// 获取部门表数据
router.get("/getDepartmentInfo", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT * FROM department`;
        let [result] = await db.execute(sql);
        res.json({
            code: 200,
            success: true,
            message: '获取部门信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取部门信息失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取部门信息失败',
            error: error.message
        });
    }
});

// 获取员工表数据
router.get("/getEmployee", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT * FROM employee`;
        let [result] = await db.execute(sql);
        res.json({
            code: 200,
            success: true,
            message: '获取员工信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取员工信息失败:', error);
        res.status(500).json({
            code: 500,
            success: false,
            message: '获取员工信息失败',
            error: error.message
        });
    }
});

// 获取用户表数据
router.get("/getUser", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT * FROM user`;
        let [result] = await db.execute(sql);
        res.json({
            code: 200,
            success: true,
            message: '获取用户信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取用户信息失败:', error);
        res.status(500).json({
            code: 500,
            success: false,
            message: '获取用户信息失败',
            error: error.message
        });
    }
});

// 获取预约状态
router.get("/getAppointmentStatus", authenticateToken, async (req, res) => {
    let status = [
        {
            key: '待确认',
            name: '待确认'
        },
        {
            key: '已确认',
            name: '已确认'
        },
        {
            key: '已取消',
            name: '已取消'
        }
    ]
    res.json({
        code: 200,
        success: true,
        message: '获取预约状态成功',
        data: status
    });
});

// 获取查询项客户list
router.get("/getCustomerList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT appointment.cust_id as 'key', customer.cust_name as 'name' FROM appointment LEFT JOIN customer ON appointment.cust_id = customer.cust_id`;
        let [result] = await db.execute(sql);
        res.json({
            code: 200,
            success: true,
            message: '获取客户列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取客户列表失败:', error);
        res.status(500).json({
            code: 500,
            success: false,
            message: '获取客户列表失败',
            error: error.message
        });
    }
});

// 获取查询项预约项目
router.get("/getProjectIdList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT appointment.project_id as 'key', project.project_name as 'name' FROM appointment LEFT JOIN project ON appointment.project_id = project.project_id`;
        let [result] = await db.execute(sql);
        res.json({
            code: 200,
            success: true,
            message: '获取预约项目成功',
            data: result
        });
    } catch (error) {
        console.error('获取预约项目失败:', error);
        res.status(500).json({
            code: 500,
            success: false,
            message: '获取预约项目失败',
            error: error.message
        });
    }
});

// 获取查询项员工list
router.get("/getEmployeeList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT appointment.emp_id as 'key', employee.emp_name as 'name' FROM appointment LEFT JOIN employee ON appointment.emp_id = employee.emp_id`;
        let [result] = await db.execute(sql);
        res.json({
            code: 200,
            success: true,
            message: '获取员工列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取员工列表失败:', error);
        res.status(500).json({
            code: 500,
            success: false,
            message: '获取员工列表失败',
            error: error.message
        });
    }
});

// 获取查询项预约状态
router.get("/getAppointmentStatusList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT status as 'key', status as 'name' FROM appointment`;
        let [result] = await db.execute(sql);
        res.json({
            code: 200,
            success: true,
            message: '获取预约状态成功',
            data: result
        });
    } catch (error) {
        console.error('获取预约状态失败:', error);
        res.status(500).json({
            code: 500,
            success: false,
            message: '获取预约状态失败',
            error: error.message
        });
    }
});

module.exports = router;